package data

import (
	"commerce/common"
	"commerce/model"
	"database/sql"
	"fmt"
	"strings"
	"time"
)

func PageComment(pageNo, pageSize int, name string) (*common.Page, error) {

	whereSql := composeCommentSearchQuerySql(name)

	row := common.DB.QueryRow("select count(*) FROM goods_comment" + whereSql)
	var totalRecords int
	if err := row.Scan(&totalRecords); err != nil {
		return nil, err
	}
	stmt, err := common.DB.Prepare("select id, goods_name, member_nick_name, created_time, show_status, sku_specs, content, member_avatar FROM goods_comment" + whereSql + " LIMIT ?, ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query((pageNo-1)*pageSize, pageSize)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var gs []model.GoodsComment
	for rows.Next() {
		g := model.GoodsComment{}
		if err := rows.Scan(&g.Id, &g.GoodsName, &g.MemberNickName, &g.CreatedTimeStr, &g.ShowStatus, &g.SkuSpecs, &g.Content, &g.MemberAvatar); err != nil {
			return nil, fmt.Errorf("评价分页数据有误:%s", err.Error())
		}
		gs = append(gs, g)
	}
	return common.NewPage(gs, pageNo, pageSize, totalRecords), nil
}

//func GetGoodsCommentById(id int) (*model.GoodsComment, error) {
//
//	sqlTpl := "select id FROM goods_comment where id = ?"
//
//	stmt, err := common.DB.Prepare(sqlTpl)
//	if err != nil {
//		return nil, err
//	}
//	defer stmt.Close()
//
//	rows, err := stmt.Query(id)
//	if err != nil {
//		return nil, err
//	}
//	defer rows.Close()
//
//	var g model.GoodsComment
//	for rows.Next() {
//		if err := rows.Scan(&g.Id); err != nil {
//			return nil, fmt.Errorf("评价id查询数据有误:%s", err.Error())
//		}
//	}
//	return &g, nil
//}

func AddGoodsComment(tx *sql.Tx, g model.GoodsComment) (int, error) {

	stmt, err := tx.Prepare(`insert into goods_comment(sku_id, goods_id, goods_name, member_nick_name, 
                     member_ip, created_time, sku_specs, content, member_avatar, comment_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
	if err != nil {
		return 0, err
	}
	defer stmt.Close()
	result, err := stmt.Exec(g.SkuId, g.GoodsId, g.GoodsName, g.MemberNickName, g.MemberIp, g.CreatedTime, g.SkuSpecs,
		g.Content, g.MemberAvatar, g.CommentType)

	if err != nil {
		return 0, fmt.Errorf("save goods_comment err: %v", err)
	}
	id, err := result.LastInsertId()

	if err != nil {
		return 0, fmt.Errorf("save goods_comment insert id err: %v", err)
	}
	return int(id), nil
}

func UpdateOrderItemCommentStatus(tx *sql.Tx, itemId int, commented int8) error {

	stmt, err := tx.Prepare(`update order_items set commented = ?, updated_time = ? where id = ?`)
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(commented, time.Now().Add(8*time.Hour), itemId)
	return nil
}

func UpdateGoodsCommentStatus(id int, status int8) error {

	sqlTpl := "update goods_comment set show_status = ? WHERE id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(status, id)

	return err
}

func GetFirstGoodsComment(skuId int, count *int) (*model.GoodsComment, error) {

	var err error
	*count, err = CountSkuComment(skuId)
	if err != nil {
		return nil, err
	}
	var stmt *sql.Stmt
	stmt, err = common.DB.Prepare("select member_nick_name, created_time, content, member_avatar FROM goods_comment where sku_id = ? and show_status = 1 limit 1")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	g := model.GoodsComment{}
	if err = stmt.QueryRow(skuId).Scan(&g.MemberNickName, &g.CreatedTimeStr, &g.Content, &g.MemberAvatar); err != nil {
		return nil, err
	}
	return &g, nil
}

func ListAppComment(skuId, pageNo, pageSize int) ([]model.GoodsComment, error) {

	stmt, err := common.DB.Prepare("select id, member_nick_name, created_time, content, member_avatar FROM goods_comment where sku_id = ? and show_status = 1 LIMIT ?, ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(skuId, (pageNo-1)*pageSize, pageSize)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var gs []model.GoodsComment
	for rows.Next() {
		g := model.GoodsComment{}
		if err := rows.Scan(&g.Id, &g.MemberNickName, &g.CreatedTimeStr, &g.Content, &g.MemberAvatar); err != nil {
			return nil, fmt.Errorf("评价app分页数据有误:%s", err.Error())
		}
		gs = append(gs, g)
	}
	return gs, nil
}

func CountSkuComment(skuId int) (int, error) {

	stmt, err := common.DB.Prepare("select count(*) FROM goods_comment where sku_id = ?")
	if err != nil {
		return 0, err
	}
	defer stmt.Close()

	var totalRecords int
	if err := stmt.QueryRow(skuId).Scan(&totalRecords); err != nil {
		return 0, err
	}
	return totalRecords, nil
}

//func ListAppGoodsComment(skuId int) ([]model.GoodsComment, error) {
//
//	stmt, err := common.DB.Prepare("select member_nick_name, created_time, content, member_avatar FROM goods_comment where sku_id = ?")
//	if err != nil {
//		return nil, err
//	}
//	defer stmt.Close()
//
//	rows, err := stmt.Query(skuId)
//	if err != nil {
//		return nil, err
//	}
//	defer rows.Close()
//
//	var gs []model.GoodsComment
//	for rows.Next() {
//		g := model.GoodsComment{}
//		if err := rows.Scan(&g.MemberNickName, g.CreatedTime, g.Content, g.MemberAvatar); err != nil {
//			return nil, fmt.Errorf("评价app有效数据有误:%s", err.Error())
//		}
//		gs = append(gs, g)
//	}
//	return gs, nil
//}

func composeCommentSearchQuerySql(name string) string {

	// 没有条件查询
	if len(name) == 0 {
		return ""
	}
	sb := strings.Builder{}
	search := "'" + strings.TrimSpace(name) + "%'"
	sb.WriteString(" WHERE (content like " + search)

	return sb.String()
}
